package com.menu.Utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult<T> implements Serializable {
    private T object;
    private Integer code;
    private String message;
    private T object1;
    private T object2;

    //成功
    public static ResponseResult success(String message, Object object) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.message = message;
        responseResult.code = 200;
        responseResult.object = object;
        return responseResult;
    }

    //成功
    public static ResponseResult success(String message, Object object, Object object1) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.message = message;
        responseResult.code = 200;
        responseResult.object = object;
        responseResult.object1 = object1;
        return responseResult;
    }

    //成功
    public static ResponseResult success(String message, Object object, Object object1,Object object2) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.message = message;
        responseResult.code = 200;
        responseResult.object = object;
        responseResult.object1 = object1;
        responseResult.object2 = object2;
        return responseResult;
    }

    //成功
    public static ResponseResult success(Object object) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.message = "成功";
        responseResult.object = object;
        responseResult.code = 200;
        return responseResult;
    }

    //失败
    public static ResponseResult error(Integer code, String message) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.message = message;
        responseResult.code = code;
        return responseResult;
    }

    //失败
    public static ResponseResult error(String msg) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.code = 501;
        responseResult.message = msg;
        return responseResult;
    }

    public static void out(HttpServletResponse response, ResponseResult r) {
        ObjectMapper mapper = new ObjectMapper();
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try {
            mapper.writeValue(response.getWriter(), r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

